package com.beyondbit.demo.controller;

import com.beyondbit.demo.entity.User;
import com.beyondbit.demo.entity.query.UserQuery;
import com.beyondbit.demo.service.BaseUserServiceException;
import com.beyondbit.demo.service.UserService;
import com.beyondbit.web.infrastructure.controller.BaseApiController;
import com.beyondbit.web.infrastructure.entity.Page;
import com.beyondbit.web.infrastructure.model.JsonResultMessage;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Author: lvfahai
 * @Date: 2020/3/10 11:23
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController extends BaseApiController {

    @Resource
    private UserService userService;

    @GetMapping("query")
    public JsonResultMessage<Page<User>> query(UserQuery userQuery) {
        val userPage = userService.query(userQuery);

        return success(userPage);
    }

    @GetMapping("{id}")
    public JsonResultMessage<User> get(@PathVariable(value = "id") String id) {
        var user = userService.get(id);

        return success(user);
    }

    @PostMapping("add")
    public JsonResultMessage add(@RequestBody @Valid User user) {
        try {
            userService.add(user);

            return success("新增成功");
        } catch (BaseUserServiceException e) {
            e.printStackTrace();
            return apiErrorResult(e);
        }
    }

    @PostMapping("update/{id}")
    public JsonResultMessage update(@PathVariable(value = "id") String id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);

        return success("修改成功");
    }

    @PostMapping("delete/{id}")
    public JsonResultMessage delete(@PathVariable(value = "id") String id) {
        userService.delete(id);

        return success("删除成功");
    }
}
